<?php

namespace App\Services\Scenic\Driver;

use App\Facades\SnowFlakeFacade;
use App\Jobs\Scenic\SyncScenicTicketDetail;
use App\Models\Common\Area\Area;
use App\Models\Common\Area\Repositories\AreaRepository;
use App\Models\Common\Area\Repositories\Interfaces\AreaRepositoryInterface;
use App\Models\Scenic\ScenicSpot;
use App\Models\Scenic\ScenicSpotGoods;
use App\Models\Scenic\ScenicSpotGoodsIntroduce;
use App\Models\Scenic\ScenicSpotGoodsPrice;
use App\Models\Scenic\ScenicSpotGoodsPriceLog;
use App\Models\Scenic\ScenicSpotGoodsProvider;
use App\Models\Scenic\ScenicSpotImage;
use App\Models\Scenic\ScenicSpotIntroduce;
use App\Models\Scenic\ScenicSpotProvider;
use App\Services\Scenic\ScenicServiceTools;
use App\Services\Scenic\TuNiuScenicService;
use App\Trip\Enums\Scenic\ScenicProvider;
use App\Trip\Geo\Amap\POI;
use App\Trip\Geo\Location;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TuniuScenicProvider implements ScenicProviderInterface
{

    private AreaRepositoryInterface $areaRepo;

    public function __construct(
    )
    {
        $this->areaRepo = new AreaRepository(new Area());
    }

    /**
     * 获取列表
     * @param string $keyword
     * @param int $page
     * @param int $pageSize
     * @param array $sort
     * @param Location $locationData
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function list(string $keyword,int $page,int $pageSize,array $sort,Location $locationData) :array
    {
        $scenicService = new TuNiuScenicService();
        $reqPage = $page;
        $reqPageSize = $pageSize;
        if ($sort['key'] == 'distance') {
            $reqPage = 1;
            $reqPageSize = 1000;
        }
        //默认取出全部相关
        $scenicRes = $scenicService->searchScenic($keyword, $reqPage, $reqPageSize);
        $scenicIds = [];
        $distanceMap = [];
        $locationMap = [];
        $total = $scenicRes->totalCount ?? 0;
        //判断数据，距离捞出全部进行
        if ($sort['key'] == 'distance') {
            $tmpData = [];
            foreach ($scenicRes->rows as $row) {
                if (!empty($row->blocation)) {
                    $blocation = ScenicServiceTools::changeLocation($row->blocation);
                    //点位转换：百度转高德
                    $geoLocation = ScenicServiceTools::bMapToGeo($blocation);
                    $scenicLocation = new Location($geoLocation);
                }else {
                    $scenicLocation = null;
                }
                //没有距离的放在最后
                $distance = 999999;
                $scenicLocationStr = '';
                if ($scenicLocation !== null && $scenicLocation->getLongitude() && $scenicLocation->getLatitude()) {
                    $distance = $locationData->getDistance($scenicLocation);
                    $scenicLocationStr = implode(',', $scenicLocation->getLocation());
                }
                if ($sort['key'] == 'distance') {
                    $tmpData[] = ['distance' => $distance, 'scenic_id' => $row->scenicId];
                }
                $distanceMap[$row->scenicId] = $distance;
                $locationMap[$row->scenicId] =  $scenicLocationStr;
            }
            $distanceCols = array_column($tmpData, 'distance');
            array_multisort($distanceCols, SORT_ASC, $tmpData);
            $offset = ($page - 1) * $pageSize;
            $tmpPage = array_slice($tmpData, $offset, $pageSize);
            foreach ($tmpPage as $item) {
                $scenicIds[] = $item['scenic_id'];
            }
        } else {
            foreach ($scenicRes->rows as $row) {
                $scenicIds[] = $row->scenicId;
            }
        }
        $data = [];
        //获取对应的
        $sysScenicList = ScenicSpotProvider::whereIn('provider_scenic_id',$scenicIds)
            ->where('provider',ScenicProvider::TUNIU->value)
            ->get();
        $sysScenicIdMap = [];
        foreach ($sysScenicList as $item){
            $sysScenicIdMap[$item->provider_scenic_id] = $item->scenic_id;
        }
        foreach ($scenicIds as $scenicId) {
            $res = $scenicService->scenicDetail($scenicId);
            $minPrice = 0;
            foreach ($res->ticketList as $ticket) {
                if ($minPrice == 0 || $minPrice > $ticket->salePrice) {
                    $minPrice = $ticket->salePrice;
                }
            }
            if (isset($sysScenicIdMap[$scenicId])){
                $sysScenicId = $sysScenicIdMap[$scenicId];
            }else{
                $scenicSpotProvider = (new ScenicSpotProvider())->registerProviderScenic(ScenicProvider::TUNIU->value,$scenicId);
                $sysScenicId = $scenicSpotProvider->scenic_id;
            }
            $bookNotice = [];
            if (!empty($res->bookNotice)) {
                $bookNotice = json_decode($res->bookNotice, true);
            }
            $scenicDescription = $res->scenicDescription ?? '';
            $scenicDescription = htmlspecialchars_decode($scenicDescription);
            $images = ScenicServiceTools::getHtmlImages($scenicDescription);
            if (!empty($res->defaultPic)) {
                array_unshift($images, ['type' => 1, 'url' => $res->defaultPic]);
            }
            $scenicLocationStr = $locationMap[$scenicId]?? '';
            if ($scenicLocationStr){
                $geo = new POI();
                $addRes = $geo->around(new Location($scenicLocationStr));
                $scenicLocationData = $addRes[0] ?? [];
            }
            $data[] = [
                'scenic_name' => $res->scenicName ?? '',
                'scenic_id' => $sysScenicId,
                'price' => $minPrice,
                'rating' => 10,
                'evaluate' => 0,
                'open_type' => 1,
                'open_hours' => $res->openTime ?? '',
                'image' => $res->defaultPic ?? '',
                'images' => $images,
                'province_name' => $scenicLocationData['pname'] ?? '',
                'city_name' => $scenicLocationData['cityname'] ?? '',
                'location' => $scenicLocationStr,
                'distance' => $distanceMap[$scenicId] ?? 0,
                'book_notice' => $bookNotice,
                'scenic_description' => $scenicDescription,
            ];
        }

        $lastPage = ceil($total / $pageSize);
        $resp = [
            'scenic_spots' => $data,
            'total' => $total,
            'current_page' => $page,
            'last_page' => $lastPage,
        ];
        return $resp;
    }


    /**
     * 推荐
     * @param int $limit
     * @param Location $locationData
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function recommend(int $limit, Location $locationData): array
    {
        $geo = new POI();
        $types = [
            '050000',
            '060000',
            '070000',
            '090000',
            '100000',
            '110000',
            '150105',
            '150203',
            '190100',
            '190300',
            '190400',
            '120000',
        ];
        $res = $geo->around($locationData, implode('|', $types));
        $ret = $res[0] ?? [];
        if (empty($ret)) {
            throw new \Exception(404, '定位信息错误');
        }
        $keyword = $ret['pname'] . $ret['cityname'] . $ret['adname'];
        $scenicService = new TuNiuScenicService();
        $scenicRes = $scenicService->searchScenic($keyword, 1, $limit);
        $data = [];
        foreach ($scenicRes->rows as $row) {
            $res = $scenicService->scenicDetail($row->scenicId);
            $minPrice = 0;
            foreach ($res->ticketList as $ticket) {
                if ($minPrice == 0 || $minPrice > $ticket->salePrice) {
                    $minPrice = $ticket->salePrice;
                }
            }
            $introduce = strip_tags(htmlspecialchars_decode($res->scenicDescription ?? ''));
            $distance = 0;
            if (!empty($row->blocation)) {
                $blocation = ScenicServiceTools::changeLocation($row->blocation);
                //点位转换：百度转高德
                $geoLocation = ScenicServiceTools::bMapToGeo($blocation);
                $distance = $locationData->getDistance(new Location($geoLocation));
            }
            $data[] = [
                'scenic_name' => $res->scenicName ?? '',
                'scenic_id' => $res->scenicId ?? '',
                'price' => $minPrice,
                'rating' => 10,
                'image' => $res->defaultPic ?? '',
                'distance' => $distance,
                'scenic_class' => ScenicServiceTools::getScenicClass($res->scenicName),
                'description' => $introduce,
            ];
        }
        return $data;
    }

    /**
     * 人气景点
     * @param int $limit
     * @param Location $locationData
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function popular(int $limit, Location $locationData): array
    {
        //todo 人气暂时和推荐一样
        return $this->recommend($limit,$locationData);
    }

    /**
     * 景点搜索
     * @param string $keyword
     * @param string $citycode
     * @param string $inputLocation
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function search(string $keyword,string $citycode,string $inputLocation): array
    {

        $city = $this->areaRepo->findCityByCode($citycode);
        if (!$city instanceof Area) {
            throw new \Exception(404, '城市编码参数错误');
        }

        $areas = Area::whereCitycode($citycode)->where('level', 'district')->get();
        $areaNames = [];
        $areaCenterMap = [];
        foreach ($areas as $area) {
            $areaNames[$area->getAdCode()] = $area->getAreaName();
            $areaCenterMap[$area->getAdCode()] = $area->center;
        }

        $cityData = [];
        $data = [];
        if (empty($inputLocation)) {
            $location = new Location($city->center);
        } else {
            $location = new Location($inputLocation);
        }
        $scenicService = new TuNiuScenicService();
        $scenicRes = $scenicService->searchScenic($keyword, 1, 1000);
        foreach ($scenicRes->rows as $row) {
            $scenicLocation = null;
            if (!empty($row->blocation)) {
                $blocation = ScenicServiceTools::changeLocation($row->blocation);
                //点位转换：百度转高德
                $geoLocation = ScenicServiceTools::bMapToGeo($blocation);
                $scenicLocation = new Location($geoLocation);
            }
            if ($scenicLocation !== null && $scenicLocation->getLongitude() && $scenicLocation->getLatitude()) {
                $geo = new POI();
                $addRes = $geo->around($scenicLocation);
                $locationData = $addRes[0] ?? [];
                $locationCityCode = $locationData['citycode'] ?? '';
                if ($citycode == $locationCityCode) {
                    $distance = $location->getDistance($scenicLocation);
                    $cityData[] = [
                        'scenic_name' => $row->scenicName,
                        'scenic_id' => $row->scenicId,
                        'distance' => $distance,
                        'scenic_class' => ScenicServiceTools::getScenicClass($row->scenicName),
                    ];
                    continue;
                }
            } else {
                foreach ($areaNames as $adcode => $areaName) {
                    if (strpos($row->address, $areaName) !== false) {
                        $center = $areaCenterMap[$adcode] ?? '';
                        $distance = 0;
                        if (!empty($center)) {
                            $distance = $location->getDistance(new Location($center));
                        }
                        $cityData[] = [
                            'scenic_name' => $row->scenicName,
                            'scenic_id' => $row->scenicId,
                            'distance' => $distance,
                            'scenic_class' => ScenicServiceTools::getScenicClass($row->scenicName),
                        ];
                        break;
                    }
                }
                continue;
            }

            $data[] = [
                'scenic_name' => $row->scenicName,
                'scenic_id' => $row->scenicId,
                'scenic_class' => ScenicServiceTools::getScenicClass($row->scenicName),
            ];
        }

        return ['city' => $cityData, 'country' => $data];
    }


    /**
     * 详情
     * @param string $scenicId
     * @param Location $inputLocation
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function detail(string $scenicId,Location $inputLocation) :array
    {
        $scenicService = new TuNiuScenicService();
        $res = $scenicService->scenicDetail($scenicId);
        $minPrice = 0;
        foreach ($res->ticketList as $ticket) {
            if ($minPrice == 0 || $minPrice > $ticket->salePrice) {
                $minPrice = $ticket->salePrice;
            }
        }

        $locationData = [];
        $location = null;
        if (!empty($res->blocation)) {
            if (!empty($res->blocation)) {
                $locationStr = ScenicServiceTools::changeLocation($res->blocation);
                $locationStr = ScenicServiceTools::bMapToGeo($locationStr);
            }
            if (!empty($locationStr)){
                $geo = new POI();
                $location = new Location($locationStr);
                $addRes = $geo->around($location);
                $locationData = $addRes[0] ?? [];
            }
        }
        $distance = 0;
        $locationStr = '';
        if ($location !== null) {
            $distance = $inputLocation->getDistance($location);
            $locationStr = implode(',', $location->getLocation());
        }
        $bookNotice = [];
        if (!empty($res->bookNotice)) {
            $bookNotice = json_decode($res->bookNotice, true);
        }
        $scenicDescription = $res->scenicDescription ?? '';
        $scenicDescription = htmlspecialchars_decode($scenicDescription);
        $images = ScenicServiceTools::getHtmlImages($scenicDescription);
        if (!empty($res->defaultPic)) {
            array_unshift($images, ['type' => 1, 'url' => $res->defaultPic]);
        }

        $data = [
            'scenic_name' => $res->scenicName ?? '',
            'scenic_id' => $scenicId,
            'price' => $minPrice,
            'rating' => 10,
            'evaluate' => 0,
            'open_type' => 1,
            'open_hours' => $res->openTime ?? '',
            'image' => $res->defaultPic ?? '',
            'images' => $images,
            'province_name' => $locationData['pname'] ?? '',
            'city_name' => $locationData['cityname'] ?? '',
            'location' => $locationStr,
            'distance' => $distance,
            'book_notice' => $bookNotice,
            'scenic_description' => trim(strip_tags(str_replace('&nbsp;', '', $scenicDescription))),
        ];

        return $data;
    }


    /**
     * 门票列表
     * @param string $scenicId
     * @return array
     * @throws \Exception
     */
    public function tickets(string $scenicId) :array
    {
        $scenicService = new TuNiuScenicService();
        $res = $scenicService->scenicDetail($scenicId);
        $data = [];
        foreach ($res->ticketList as $ticket) {
            $data[] = [
                'ticket_id' => $ticket->productId,
                'scenic_id' => $res->scenicId,
                'ticket_name' => $ticket->productName,
                'price' => $ticket->salePrice,
                'market_price' => $ticket->webPrice,
                //todo 落地走db，才赋值
                'ticket_type' => '',
                'ticket_delivery' => '',
                'sold_count' => 0,
                'book' => [
                    'notice' => '',
                    'rc_rule' => '',
                ],
                'introduction' => '',
                'refund_type' => '',
            ];
        }

        return $data;
    }


    /**
     * 门票详情
     * @param string $ticketId
     * @return array
     * @throws \Exception
     */
    public function ticket(string $ticketId) :array
    {
        $scenicService = new TuNiuScenicService();
        $res = $scenicService->ticketDetail($ticketId);
//        $cacheKey = sprintf(config("trip.scenic.scenic_sale_key"),$citycode);
//        $soldCount = Redis::ZSCORE($cacheKey,$scenicId);
        $ticketData = [
            'ticket_id' => $res->productId,
            'scenic_id' => $res->scenicId,
            'ticket_name' => $res->productName,
            'price' => $res->salePrice,
            'market_price' => $res->webPrice,
            'enter_type' => $res->admissionVoucher->admissionVoucherCode,
            'enter_type_desc' => $res->admissionVoucher->admissionVoucherDesc,
            'enter_sms_msg' => $res->smsMessage,
            'ticket_type' => $res->mpType,
            'ticket_sub_type' => $res->subType,
            'ticket_delivery' => $res->drawType,
            //todo 根据实际订单处理销量
            'sold_count' => 9999,
            'book' => [
                'notice' => $res->bookNotice,
                'advance_day' => $res->advanceDay,
                'advance_hour' => $res->advanceHour,
                'min_num' => $res->limitNumLow,
                'max_num' => $res->limitNumHigh,
                'passenger_limit' => $res->custInfoLimit,
                'identity_type' => $res->certificateType,
                'refund_rule' => $res->mpLossInfo,
            ],
            'introduction' => $res->info,
            'valid_date' => '',
            'refund_type' => strpos($res->mpLossInfo, '随时退') === false ? 2 : 1,
        ];
        $calendar = [];
        foreach ($res->priceCalendar as $priceCalendar) {
            $calendar[] = [
                'date' => $priceCalendar->departDate,
                'price' => $priceCalendar->salePrice,
                'child_price' => $priceCalendar->childPrice ?? 0,
            ];
        }
        return ['ticket' => $ticketData, 'calendar' => $calendar];
    }


    /**
     * 同步景点数据到db
     * @param string $scenicId
     * @return bool
     */
    public function scenicToDb(string $scenicId) :bool
    {
        //获取对应的三方景点详情
        $scenicService = new TuNiuScenicService();
        try {
            $data = $scenicService->scenicDetail($scenicId);
        } catch (\Exception $exception) {
            $spotProviderModel = ScenicSpotProvider::where('provider', ScenicProvider::TUNIU->value)
                ->where('provider_scenic_id', $scenicId)->first();
            if ($spotProviderModel instanceof ScenicSpotProvider){
                ScenicSpot::where('scenic_id', $spotProviderModel->scenic_id)->update(['open_type'=>2,'updated_at'=>time()]);
            }
            return false;
        }
        $sysScenicId = '';
        //景点id关联三方
        DB::transaction(function () use ($data,$scenicId) {
            //是否新增数据
            $isNew = false;
            $spotProviderModel = ScenicSpotProvider::where('provider', ScenicProvider::TUNIU->value)
                ->where('provider_scenic_id', $scenicId)->first();
            if (!$spotProviderModel instanceof ScenicSpotProvider) {
                $spotProviderModel = new ScenicSpotProvider();
                $spotProviderModel->scenic_id = SnowFlakeFacade::id();
                $spotProviderModel->provider = ScenicProvider::TUNIU->value;
                $spotProviderModel->provider_scenic_id = $scenicId;
                $spotProviderModel->created_at = time();
                $isNew = true;
            }
            $spotProviderModel->updated_at = time();
            $spotProviderModel->save();
            $locationStr = $data->blocation ?? '';
            $locationStr = ScenicServiceTools::changeLocation($locationStr);
            if (!empty($locationStr)) {
                $locationStr = ScenicServiceTools::bMapToGeo($locationStr);
            }
            //景点信息
            $scenicSpotModel = ScenicSpot::where('scenic_id', $spotProviderModel->scenic_id)->first();
            if (!$scenicSpotModel instanceof ScenicSpot) {
                $scenicSpotModel = new ScenicSpot();
                $scenicSpotModel->scenic_id = $spotProviderModel->scenic_id;
                $scenicSpotModel->star = '';
                $scenicSpotModel->rating = '';
                $scenicSpotModel->province = '';
                $scenicSpotModel->city = '';
                $scenicSpotModel->area = '';
                $scenicSpotModel->business_area = '';
                $location = new Location($locationStr);
                if ($location->getLongitude() && $location->getLatitude()){
                    $geo = new POI();
                    $addRes = $geo->around($location);
                    $locationData = $addRes[0] ?? [];
                    $scenicSpotModel->province = $locationData['pcode'] ?? '';
                    $scenicSpotModel->city = $locationData['citycode'] ?? '';
                    $scenicSpotModel->area = $locationData['adcode'] ?? '';
                    $scenicSpotModel->business_area = '';
                    //新数据丢入城市code关联的redis score
                    if ($isNew) {
                        $orderSaleCacheKey = sprintf(config("trip.scenic.scenic_sale_key"), $scenicSpotModel->city);
//                        $orderSale = Redis::ZSCORE($orderSaleCacheKey,$spotProviderModel->scenic_id);
//                        if ($orderSale === false){
                        Redis::zadd($orderSaleCacheKey, 0, $spotProviderModel->scenic_id);
//                        }
                    }
                }
                $scenicSpotModel->created_at = date('Y-m-d H:i:s');
            }
            $scenicSpotModel->scenic_name = $data->scenicName ?? '';
            $scenicSpotModel->address = $data->scenicAddress ?? '';
            $scenicSpotModel->location = ScenicServiceTools::dealLocation($locationStr);
            $scenicSpotModel->blocation = ScenicServiceTools::dealLocation(ScenicServiceTools::changeLocation($data->blocation ?? ''));
            $scenicSpotModel->traffic = $data->trafficBus ?? '';
            $scenicSpotModel->introduction = $data->scenicDescription ?? '';
            $scenicSpotModel->image = $data->defaultPic ?? '';
            $scenicSpotModel->open_hours = $data->openTime ?? '';
            $scenicSpotModel->sentence = $data->recommend ?? '';
            $scenicSpotModel->book_notice = $data->bookNotice ?? '';
            $scenicSpotModel->open_type = 1;
            $scenicSpotModel->updated_at = date('Y-m-d H:i:s');
            $scenicSpotModel->save();
            //景点详情
            $introduce = trim(strip_tags(str_replace('&nbsp;','',htmlspecialchars_decode($data->scenicDescription ?? ''))));
            $spotIntroduceModel = ScenicSpotIntroduce::where('scenic_id', $spotProviderModel->scenic_id)->first();
            if (!$spotIntroduceModel instanceof ScenicSpotIntroduce) {
                $spotIntroduceModel = new ScenicSpotIntroduce();
                $spotIntroduceModel->scenic_id = $spotProviderModel->scenic_id;
                $spotIntroduceModel->created_at = time();
            }
            $spotIntroduceModel->introduce = $introduce;
            $spotIntroduceModel->updated_at = time();
            $spotIntroduceModel->save();
            //景点图片
            //先删除，再增加
            ScenicSpotImage::where('scenic_id', $spotProviderModel->scenic_id)->delete();
            if (!empty($data->defaultPic)){
                $headerImageData = new ScenicSpotImage([
                    'scenic_id' => $spotProviderModel->scenic_id,
                    'type' => 1,
                    'origin_url' => $data->defaultPic,
                    'url' => '',
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
                $headerImageData->save();
            }
            $images = ScenicServiceTools::getHtmlImages(htmlspecialchars_decode($data->scenicDescription));
            if ($images) {
                foreach ($images as $image) {
                    if (empty($image)){
                        continue;
                    }
                    $imageData = new ScenicSpotImage([
                        'scenic_id' => $spotProviderModel->scenic_id,
                        'type' => $image['type'] ?? 2,
                        'origin_url' => $image['url'] ?? '',
                        'url' => '',
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]);
                    $imageData->save();
                }
            }
            $sysScenicId = $spotProviderModel->scenic_id;
        });
        //推入门票同步队列
        if ($sysScenicId && !empty($data->ticketList)) {
            foreach ($data->ticketList as $ticket) {
                SyncScenicTicketDetail::dispatch($sysScenicId, $ticket->productId,ScenicProvider::TUNIU->value)->onQueue('{syncTuNiuScenicTicket}');
            }
        }
        return true;
    }


    /**
     * 同步数据到db
     * @param $scenicId
     * @param $productId
     * @return bool
     */
    public function ticketToDb($scenicId,$productId) :bool
    {
        $scenicService = new TuNiuScenicService();
        try {
            $row = $scenicService->ticketDetail($productId);
        }catch (\Exception $exception){
            $spotProviderModel = ScenicSpotGoodsProvider::where('provider_ticket_id', $productId)
                ->where('scenic_id', $scenicId)
                ->where('provider', ScenicProvider::TUNIU->value)
                ->first();
            if ($spotProviderModel instanceof ScenicSpotGoodsProvider){
                ScenicSpotGoods::where('ticket_id', $spotProviderModel->ticket_id)
                    ->where('scenic_id',$spotProviderModel->scenic_id)
                    ->update([
                    'goods_status'=>2,
                    'goods_status_desc'=>$exception->getMessage(),
                    'updated_at'=>time()
                ]);
            }
            return false;
        }
        DB::transaction(function () use ($row,$productId,$scenicId) {
            //关联数据获取
            $isNew = false;
            $scenicSpotGoodsProvider = ScenicSpotGoodsProvider::where('provider_ticket_id', $productId)
                ->where('scenic_id', $scenicId)
                ->where('provider', ScenicProvider::TUNIU->value)
                ->first();
            $oldSalePrice = 0;
            $oldProviderSalePrice = 0;
            if (!$scenicSpotGoodsProvider instanceof ScenicSpotGoodsProvider) {
                $scenicSpotGoodsProvider = new ScenicSpotGoodsProvider();
                $scenicSpotGoodsProvider->ticket_id = SnowFlakeFacade::id();
                $scenicSpotGoodsProvider->scenic_id = $scenicId;
                $scenicSpotGoodsProvider->provider = ScenicProvider::TUNIU->value;
                $scenicSpotGoodsProvider->provider_ticket_id = $productId;
                $scenicSpotGoodsProvider->goods_status = 1;
                $scenicSpotGoodsProvider->goods_status_desc = '';
                $scenicSpotGoodsProvider->created_at = time();
                $isNew = true;
            }else{
                $oldSalePrice = $scenicSpotGoodsProvider->sale_price;
                $oldProviderSalePrice = $scenicSpotGoodsProvider->provider_sale_price;
            }
            $scenicSpotGoodsProvider->sale_price = $row->salePrice;
            $scenicSpotGoodsProvider->provider_sale_price = $row->salePrice;
            $scenicSpotGoodsProvider->updated_at = time();
            $scenicSpotGoodsProvider->save();
            //价格变化，添加日志
            if (!$isNew && $oldSalePrice != $row->salePrice){
                $scenicSpotGoodsPriceLog = new ScenicSpotGoodsPriceLog();
                $scenicSpotGoodsPriceLog->ticket_id = $scenicSpotGoodsProvider->ticket_id;
                $scenicSpotGoodsPriceLog->scenic_id = $scenicSpotGoodsProvider->scenic_id;
                $scenicSpotGoodsPriceLog->provider = $scenicSpotGoodsProvider->provider;
                $scenicSpotGoodsPriceLog->provider_ticket_id = $scenicSpotGoodsProvider->provider_ticket_id;
                $scenicSpotGoodsPriceLog->sale_price = $oldSalePrice;
                $scenicSpotGoodsPriceLog->provider_sale_price = $oldProviderSalePrice;
                $scenicSpotGoodsPriceLog->created_at = time();
                $scenicSpotGoodsPriceLog->update_at = time();
                $scenicSpotGoodsPriceLog->save();
            }
            //添加或更新价格
            $scenicSpotGoodsPrice = ScenicSpotGoodsPrice::where('ticket_id', $scenicSpotGoodsProvider->ticket_id)
                ->where('scenic_id', $scenicId)
                ->where('provider', ScenicProvider::TUNIU->value)
                ->first();
            if (!$scenicSpotGoodsPrice instanceof ScenicSpotGoodsPrice){
                $scenicSpotGoodsPrice = new ScenicSpotGoodsPrice();
                $scenicSpotGoodsPrice->scenic_id = $scenicSpotGoodsProvider->scenic_id;
                $scenicSpotGoodsPrice->ticket_id = $scenicSpotGoodsProvider->ticket_id;
                $scenicSpotGoodsPrice->provider = $scenicSpotGoodsProvider->provider;
                $scenicSpotGoodsPrice->created_at = time();
            }
            $scenicSpotGoodsPrice->sale_price = $row->salePrice;
            $scenicSpotGoodsPrice->provider_sale_price = $row->salePrice;
            $scenicSpotGoodsPrice->date = date('Y-m-d');
            $scenicSpotGoodsPrice->updated_at = time();
            $scenicSpotGoodsPrice->save();
            //门票说明更新
            $scenicSpotGoodsIntroduce = ScenicSpotGoodsIntroduce::where('ticket_id', $scenicSpotGoodsProvider->ticket_id)
                ->where('scenic_id', $scenicId)
                ->first();
            if (!$scenicSpotGoodsIntroduce instanceof ScenicSpotGoodsIntroduce){
                $scenicSpotGoodsIntroduce = new ScenicSpotGoodsIntroduce();
                $scenicSpotGoodsIntroduce->ticket_id = $scenicSpotGoodsProvider->ticket_id;
                $scenicSpotGoodsIntroduce->scenic_id = $scenicSpotGoodsProvider->scenic_id;
                $scenicSpotGoodsIntroduce->created_at = time();
            }
            $scenicSpotGoodsIntroduce->introduce = $row->info;
            $scenicSpotGoodsIntroduce->updated_at = time();
            $scenicSpotGoodsIntroduce->save();
            //门票更新
            $scenicSpotGoods = ScenicSpotGoods::where('ticket_id', $scenicSpotGoodsProvider->ticket_id)
                ->first();
            if (!$scenicSpotGoods instanceof ScenicSpotGoods){
                $scenicSpotGoods = new ScenicSpotGoods();
                $scenicSpotGoods->scenic_id = $scenicSpotGoodsProvider->scenic_id;
                $scenicSpotGoods->ticket_id = $scenicSpotGoodsProvider->ticket_id;
                $scenicSpotGoods->created_at = time();
            }
            $scenicSpotGoods->ticket_name = $row->productName;
            $scenicSpotGoods->ticket_delivery = $row->drawType;
            $scenicSpotGoods->ticket_type = $row->mpType;
            $scenicSpotGoods->advance_day = $row->advanceDay;
            $scenicSpotGoods->advance_hour = $row->advanceHour;
            $scenicSpotGoods->min_num = $row->limitNumLow;
            $scenicSpotGoods->max_num = $row->limitNumHigh;
            $identityType = ScenicServiceTools::enIdentityType($row->certificateType);
            $scenicSpotGoods->identity_type = $identityType;
            $scenicSpotGoods->passenger_limit = $row->custInfoLimit;
            $scenicSpotGoods->refund_rule = $row->mpLossInfo;
            $scenicSpotGoods->refund_type = strpos($row->mpLossInfo,'随时退') === false ? 2 : 1;
            $scenicSpotGoods->book_notice = $row->bookNotice;
            $scenicSpotGoods->updated_at = time();
            $scenicSpotGoods->save();
        });

        return true;
    }

}
